import React, {useState, useEffect} from "react";
import marked from "marked";
import axios from "axios";

import "../static/css/AddArticle.css";
import {Row, Col, Input, Select, Button, DatePicker, message, Spin} from "antd";
import servicePath from "../config/apiUrl";

const {Option} = Select
const {TextArea} = Input

marked.setOptions({
    renderer: marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
});


function AddArticle(props) {

    const [articleId, setArticleId] = useState(-1)  // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
    const [articleTitle, setArticleTitle] = useState('')   //文章标题
    const [articleContent, setArticleContent] = useState('')  //markdown的编辑内容
    const [markdownContent, setMarkdownContent] = useState('预览内容') //html内容
    const [introducemd, setIntroducemd] = useState()            //简介的markdown内容
    const [introducehtml, setIntroducehtml] = useState('等待编辑') //简介的html内容
    const [showDate, setShowDate] = useState()   //发布日期
    const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
    const [selectedType, setSelectType] = useState() //选择的文章类别
    const [isSave, setIsSave] = useState(false)  //是否提交
    const [TypeTitle, setTypeTitle] = useState("文章类别")

    useEffect(() => {
        getTypeInfo();
        //获取文章id
        console.log(props);
        let tmpId = props.match.params.id;
        if (tmpId) {
            setArticleId(tmpId);
            getArticleById(tmpId);
        }
    }, []);


    const changeContent = (e) => {
        setArticleContent(e.target.value)
        let html = marked(e.target.value)
        setMarkdownContent(html)
    }

    const changeIntroduce = (e) => {
        setIntroducehtml(marked(e.target.value));
        setIntroducemd(e.target.value);
    }

    //获取文章信息
    const getTypeInfo = () => {
        let token = localStorage.getItem("openId");
        let user = localStorage.getItem("user");

        axios({
            method: 'get',
            url: servicePath.getTypeInfo,
            params: {
                "token": token,
                "user": user
            }

        }).then(
            res => {
                if (res.status === 200) {
                    setTypeInfo(res.data.Data);
                }
            }
        ).catch(function () {
            window.location.replace("/");
            localStorage.clear();
        })
    }

    const selectTypeHandle = (value) => {
        setSelectType(value);
        setTypeTitle(value);
    }

    const saveArticle = () => {
        setIsSave(true);
        setTimeout(() => {
            setIsSave(false)
        }, 500)
        if (!selectedType || selectedType === "文章类别") {
            message.error("必须选择文章类型");
            return false;
        } else if (!articleTitle) {
            message.error("必须有文章标题");
            return false;
        } else if (!articleContent) {
            message.error("文章内容不可为空");
            return false;
        } else if (!showDate) {
            message.error("发布日期不可为空");
            return false;
        } else if (!introducemd) {
            message.error("文章简介不可为空");
            return false;
        }

        let token = localStorage.getItem("openId");
        let user = localStorage.getItem("user");
        let dataPros = new FormData;
        let saveDate = (new Date(showDate.replace('-', '/')).getTime()) / 1000;

        dataPros.append("typeId", selectedType);
        dataPros.append("articleTitle", articleTitle);
        dataPros.append("articleContent", articleContent);
        dataPros.append("showDate", saveDate);
        dataPros.append("introducemd", introducemd);

        if (articleId === -1) {
            axios({
                method: "post",
                url: servicePath.addArticle,
                params: {
                    "token": token,
                    "user": user
                },
                data: dataPros
            }).then(res => {
                if (res.status === 200) {
                    message.success("保存成功");
                    setArticleId(res.data.articleId);
                }
            }).catch(err => {
                if (err.response.status === 401) {
                    message.error("认证错误");
                    localStorage.clear();
                } else {
                    message.error("保存失败");
                }
            })
        } else {
            dataPros.append("articleId", articleId);
            axios({
                method: "post",
                url: servicePath.updateArticle,
                params: {
                    "token": token,
                    "user": user
                },
                data: dataPros
            }).then(res => {
                if (res.status === 200) {
                    message.success("修改成功");
                }
            }).catch(err => {
                if (err.response.status === 401) {
                    message.error("认证错误");
                    localStorage.clear();
                } else {
                    message.error("修改失败");
                }
            })
        }


    }

    const getArticleById = (id) => {
        axios({
            method: "get",
            url: servicePath.getArticleById,
            params: {
                id: id,
            }
        }).then(
            res => {
                let article = res.data.Data;
                setArticleTitle(article.Title);
                setArticleContent(article.ArticleContent);
                let html = marked(article.ArticleContent);
                setMarkdownContent(html);
                setIntroducemd(article.Introduce);
                let tmpInt = marked(article.Introduce);
                setIntroducehtml(tmpInt);
                setSelectType(article.TypeId);
                setTypeTitle(article.TypeTitle)
            }
        )
    }

    return (
        <div>

            <Row gutter={5}>
                <Col span={18}>
                    <Row gutter={10}>
                        <Col span={20}>
                            <Input
                                onChange={e => {
                                    setArticleTitle(e.target.value);
                                }}
                                value={articleTitle}
                                placeholder={"博客标题"}
                                size={"large"}/>
                        </Col>
                        <Col span={4}>
                            &nbsp;
                            <Select defaultValue={TypeTitle} size={"large"} onChange={selectTypeHandle}
                                    value={TypeTitle}>
                                {
                                    typeInfo.map((item, index) => {
                                        return (<Option key={index} value={item.ID}>{item.TypeName}</Option>)
                                    })
                                }

                            </Select>
                        </Col>

                    </Row>
                    <br/>
                    <Row gutter={10}>
                        <Col span={12}>
                            <TextArea
                                value={articleContent}
                                className="markdown-content"
                                rows={35}
                                onChange={changeContent}
                                onPressEnter={changeContent}
                                placeholder="文章内容"
                            />
                        </Col>
                        <Col span={12}>
                            <div
                                className="show-html"
                                dangerouslySetInnerHTML={{__html: markdownContent}}>

                            </div>
                        </Col>
                    </Row>
                </Col>

                <Col span={6}>
                    <Row>
                        <Col span={24}>
                            <Spin tip="Save...." spinning={isSave}>
                                <Button size={"large"}>暂存文章</Button>&nbsp;
                                <Button type={"primary"} size={"large"} onClick={saveArticle}>发布文章</Button>
                            </Spin>
                            <br/>
                        </Col>

                        <Col span={24}>
                            <br/>
                            <TextArea
                                rows={4}
                                value={introducemd}
                                onChange={changeIntroduce}
                                onPressEnter={changeIntroduce}
                                placeholder="文章简介"
                            /><br/>
                            <div
                                className="introduce-html"
                                dangerouslySetInnerHTML={{__html: introducehtml}}>
                            </div>
                        </Col>

                        <Col span={12}>
                            <div className={"date-select"}>
                                <DatePicker
                                    onChange={(date, dateString) => {
                                        setShowDate(dateString);
                                    }}
                                    placeholder={"发布日期"}
                                    size={"large"}/>

                            </div>

                        </Col>

                    </Row>
                </Col>
            </Row>

        </div>
    )
}


export default AddArticle













